#include "maindialog.h"
#include "ui_maindialog.h"
#include "worker.h"

#include <QThread>
#include <QFile>
#include <QMessageBox>
#include <QFileDialog>

MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);

    setWindowTitle("文件复制工具");

    ui->pbCopyProgress->setRange(0,100);
    ui->pbCopyProgress->setValue(0);

    copyThr = new QThread(this);
    Worker* w = new Worker();

    w->moveToThread(copyThr);

    //连接信号
    connect(this, &MainDialog::startCopy, w, &Worker::copyFile);
    connect(w, &Worker::updateCopyProgress, this, &MainDialog::updateCopyProgress);
    connect(w, &Worker::copyFinished, this, &MainDialog::copyFinished);

    connect(copyThr, &QThread::finished, w, &QObject::deleteLater);

    copyThr->start();


}

MainDialog::~MainDialog()
{
    delete ui;

    copyThr->quit();
    copyThr->wait();

}



void MainDialog::on_btnSelectSourceFile_clicked()
{
    QString srcFilePath = QFileDialog::getOpenFileName(this, "请选择要拷贝的文件");
    ui->edtSourceFilePath->setText(srcFilePath);
}

void MainDialog::on_btnSelectDestFile_clicked()
{
    QString srcFilePath = ui->edtSourceFilePath->text();

    QString destFilePath = QFileDialog::getOpenFileName(this, "请选择目标文件 ", srcFilePath);
    ui->edtDestFilePath->setText(destFilePath);
}

void MainDialog::on_btnCopy_clicked()
{
    QString srcFilePath = ui->edtSourceFilePath->text();
    QString destFilePath = ui->edtDestFilePath->text();

    QFile f1(srcFilePath), f2(destFilePath);

    if(!f1.open(QIODevice::ReadOnly))
    {
        QMessageBox::critical(this, "温馨提示", "源文件不可读或者不存在");
        ui->edtSourceFilePath->setFocus();
        return;
    }
    f1.close();

    if(!f2.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        QMessageBox::critical(this, "温馨提示", "目标文件不可创建或不能写");
        ui->edtDestFilePath->setFocus();
        return;
    }
    f2.close();

    ui->btnCopy->setDisabled(true);
    ui->btnCopy->setText("拷贝中...");

    emit startCopy(srcFilePath, destFilePath);


}

void MainDialog::updateCopyProgress(int progress)
{
    ui->pbCopyProgress->setValue(progress);
}

void MainDialog::copyFinished()
{
    QMessageBox::information(this, "温馨提示", "文件拷贝完成");

    ui->btnCopy->setEnabled(true);
    ui->btnCopy->setText("开始拷贝");
    ui->pbCopyProgress->setValue(0);
}
